﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Management;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.Win32;
using System.Collections;
using System.Text.RegularExpressions;
using System.Data.OleDb;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraExport;

namespace Waker.Common
{
    public sealed class Util
    {
        public const string REGKEY = "Software\\Clubank\\Golf2012";
        //public const string CARD_KEY = "SEIN2K";//card access key
        //public const string ESC_SEC = ",13,14,15,"; //不做初始化的扇区号码，用逗号隔开
        //public const long CARD_BAUD = 9600;         //IC卡访问波特率
        //public const string CARD_ID = "TSPGC";//clubank card identity
        //public const byte CARDNO_SECTOR = 0;// sector where card no stored.
        const string DATEFORMAT = "yyyy-MM-dd";//年月日
        const string TIMEFORMAT = "1900-01-01 HH:mm:00";//1900-01-01 时分
        const string DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss.fff";//年月日 时分秒毫秒
        const string ENCRYPT_KEY = "coolxiaomi";// 密钥，8个字符 


        /// <summary>
        /// 判断是否为数字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsNumber(string s)
        {
            int Flag = 0;
            char[] str = s.ToCharArray();
            for (int i = 0; i < str.Length; i++)
            {
                if (Char.IsNumber(str[i]))
                {
                    Flag++;
                }
                else
                {
                    Flag = -1;
                    break;
                }
            }
            if (Flag > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 日期格式化字符串(年-月-日) 
        /// </summary>
        public static string DateFormatString
        {
            get { return DATEFORMAT; }
        }

        /// <summary>
        /// 时间格式化字符串(1900-01-01 时:分) 
        /// </summary>
        public static string TimeFormatString
        {
            get { return TIMEFORMAT; }
        }

        /// <summary>
        /// 日期时间格式化字符串(年-月-日 时:分:秒.毫秒) 
        /// </summary>
        public static string DateTimeFormatString
        {
            get { return DATETIMEFORMAT; }
        }

        /// <summary>
        /// 获取No(年月日加时间)例如(0020121030153045)
        /// </summary>
        /// <returns></returns>
        public static string GetOrderNo()
        {
            string getNo = "";
            string getStrTime = DateTime.Now.ToLongTimeString();
            string getStrDate = DateTime.Now.ToShortDateString();
            string words = getStrDate + getStrTime;

            string[] split = words.Split(new char[] { '-', ':', '/' });

            foreach (string s in split)
            {
                getNo += s;
            }
            return funZero(getNo, 16);
        }
        public static string funZero(string input, int length)
        {
            string strReturn = input;
            for (int i = 0; i < length - input.Length; i++)
            {
                strReturn = "0" + strReturn;
            }
            return strReturn;
        }

        /// <summary>
        /// 64位DES加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptDES(string input)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(ENCRYPT_KEY.Substring(0, 8));
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//对称算法的初始化向量，64位（8个字节）

            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] bInput = Encoding.UTF8.GetBytes(input);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(bKey, IV), CryptoStreamMode.Write);
                cs.Write(bInput, 0, bInput.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 64位DES解密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string DecryptDES(string input)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(ENCRYPT_KEY.Substring(0, 8));
            byte[] len = new Byte[input.Length];
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//对称算法的初始化向量，64位（8个字节）
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                len = Convert.FromBase64String(input);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bKey, IV), CryptoStreamMode.Write);
                cs.Write(len, 0, len.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch
            {
                return string.Empty;
            }
        }


        public static string GetLocalMachine()
        {
            return string.Format("{0}({1})", Dns.GetHostName(), GetLocalIPAddress());
        }
        public static string GetLocalString(Dictionary<String, String> d, string s)
        {
            if (d.ContainsKey(s) && d[s] != null)
            {
                return d[s];
            }
            return null;
        }

        /// <summary>
        /// 读取注册表
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object GetRegValue(string key)
        {
            return GetRegValue(key, null);
        }

        public static object GetRegValue(string key, object defValue)
        {
            object ret = defValue;
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(REGKEY);
            if (rk != null)
            {
                ret = rk.GetValue(key);
            }
            if (ret != null)
            {
                return ret;
            }
            return defValue;
        }
        /// <summary>
        /// 写注册表
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetRegValue(string key, object value)
        {
            RegistryKey rk = Registry.CurrentUser.CreateSubKey(REGKEY);
            rk.SetValue(key, value);
        }

        //public static Icon GetSystemIcon(int iconIndex)
        //{
        //    string fName = Environment.SystemDirectory + "\\shell32.dll";
        //    IntPtr[] hLarge = new IntPtr[1] { IntPtr.Zero };
        //    IntPtr[] hSmall = new IntPtr[1] { IntPtr.Zero };
        //    Win32.ExtractIconEx(fName, iconIndex, hLarge, hSmall, 1);
        //    Icon icon = (Icon)Icon.FromHandle(hLarge[0]).Clone();
        //    Win32.DestroyIcon(hLarge[0]);
        //    Win32.DestroyIcon(hSmall[0]);
        //    return icon;
        //}

        /// <summary>
        /// 执行DataTable中的查询返回新的DataTable
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public static DataTable GetNewDataTable(DataTable dt, string condition)
        {
            DataTable newdt = new DataTable();
            newdt = dt.Clone();
            DataRow[] dr = dt.Select(condition);
            for (int i = 0; i < dr.Length; i++)
            {
                newdt.ImportRow((DataRow)dr[i]);
            }
            return newdt;//返回的查询结果
        }
        /// <summary>
        /// 获得应用程序的根路径
        /// </summary>
        public static string ApplicationPath
        {
            get
            {
                return Directory.GetCurrentDirectory();
            }
        }
        /// <summary>
        /// 获取ICon
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        //public static Icon GetIcon(string path)
        //{
        //    try
        //    {
        //        System.IO.StreamReader sm = new System.IO.StreamReader(path);
        //        Icon icon = new Icon(sm.BaseStream);
        //        return icon;
        //    }
        //    catch
        //    {
        //        return null;
        //    }
        //}

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        //public static Image GetImageFile(string path)
        //{
        //    Image im = new Bitmap(path);
        //    return im;
        //}

        /// <summary>
        /// 获取资源图片
        /// </summary>
        /// <param name="path"></param> 
        /// <returns></returns>
        public static Image GetIconResource(string path, int width, int height)
        {
            try
            {
                //Stream s = Assembly.GetCallingAssembly().GetManifestResourceStream(path);
                //if (s == null)
                //{
                //    s = Assembly.GetCallingAssembly().GetManifestResourceStream("Clubank.Golf.Images.Icon.system.ico");
                //}
                //Icon i = new Icon(s, new Size(width, width));
                //return i.ToBitmap();
                if (!File.Exists(path))
                    return null;
                //using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open)))
                //{
                //    var bytes = reader.ReadBytes(Convert.ToInt32(new FileInfo(path).Length));
                //    reader.Close(); ;
                //    //var icon = new Icon(new MemoryStream(bytes), new Size(width, height));
                //    //return icon.ToBitmap();

                //}
                return Image.FromFile(path);
            }
            catch
            {
                return null;
            }
        }

        //public static Image GetIconResource(string path)
        //{
        //    Stream s = Assembly.GetCallingAssembly().GetManifestResourceStream(path);
        //    if (s == null)
        //    {
        //        s = Assembly.GetCallingAssembly().GetManifestResourceStream("Clubank.Golf.Images.Icon.system.ico");
        //    }
        //    if (s != null)
        //    {
        //        Icon i = new Icon(s);
        //        return i.ToBitmap();
        //    }
        //    return null;
        //}

        //public static Image GetImgResource(string path)
        //{
        //    Image im = new Bitmap(Assembly.GetCallingAssembly().GetManifestResourceStream(path));
        //    return im;
        //}


        /// <summary> 
        /// 将 Stream 写入文件 
        /// </summary> 
        public static void StreamToFile(Stream stream, string fileName)
        {
            // 把 Stream 转换成 byte[] 
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);

            // 把 byte[] 写入文件 
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(bytes);
            bw.Close();
            fs.Close();
        }

        /// <summary>
        /// 比较两个hashtable是否相同
        /// </summary>
        /// <param name="hs"></param>
        /// <param name="hsold"></param>
        /// <returns></returns>
        public static bool CompanyHashTable(Hashtable hs, Hashtable hsold)
        {
            if (hs.Count != hsold.Count)
            {
                return false;
            }
            else
            {
                foreach (DictionaryEntry hsitem in hs)
                {
                    if (hsold.ContainsKey(hsitem.Key.ToString()))
                    {
                        if (Convert.ToDecimal(hsold[hsitem.Key.ToString()]) != Convert.ToDecimal(hsitem.Value))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 舍入计算
        /// </summary>
        /// <param name="d">元数据</param>
        /// <param name="len">舍入位数</param>
        /// <param name="type">方式（0：四舍五入；1：全舍；2：全入）</param>
        /// <returns></returns>
        public static decimal Round(decimal d, int len, string type)
        {
            if (type == "0")
                return round0(d, len);
            else if (type == "1")
                return round1(d, len);
            else
                return round2(d, len);
        }


        //四舍五入
        private static decimal round0(decimal d, int l)
        {
            return decimal.Round(d, l, MidpointRounding.AwayFromZero);
        }

        //全舍
        private static decimal round1(decimal d, int l)
        {
            if (d == 0)
                return d;
            decimal x1 = round0(d, l);
            if (x1 <= d)
            {
                return x1;
            }

            decimal x = 1;
            for (int i = 0; i < l; i++)
            {
                x = x * 10;
            }

            d = d - (decimal)0.5 / x;
            return decimal.Round(d, l);
        }
        //全入
        private static decimal round2(decimal d, int l)
        {
            if (d == 0)
                return d;
            decimal x1 = round0(d, l);
            if (x1 >= d)
            {
                return x1;
            }

            decimal x = 1;
            for (int i = 0; i < l; i++)
            {
                x = x * 10;
            }

            d = d + (decimal)0.5 / x;
            return decimal.Round(d, l);
        }

        public static string GetMD5(string input)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] b = md5.ComputeHash(UTF8Encoding.Default.GetBytes(input));
            string t2 = BitConverter.ToString(b);
            t2 = t2.Replace("-", "");
            return t2.ToLower();
        }

        public static string GetHardwareInfo()
        {
            ManagementObject cpu = GetFirstMO("SELECT ProcessorId FROM Win32_Processor");
            ManagementObject mac = GetFirstMO("SELECT MACAddress FROM Win32_NetworkAdapterConfiguration");
            //string mac = GetLocalMacAddress();
            ManagementObject bio = GetFirstMO("SELECT Name FROM Win32_BIOS");
            ManagementObject mem = GetFirstMO("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem");
            ManagementObject mbd = GetFirstMO("SELECT DeviceId FROM Win32_MotherboardDevice");
            ManagementObject hdi = GetFirstMO("SELECT Caption, DeviceID FROM Win32_DiskDrive");
            ManagementObject cdr = GetFirstMO("SELECT Name FROM Win32_CDROMDrive");

            string str = Environment.MachineName;
            //str += GetLocalIPAddress();
            //str += mac;
            str += cpu["ProcessorId"];
            str += mac["MACAddress"];
            str += bio["Name"];
            str += mbd["DeviceId"];
            str += mem["TotalPhysicalMemory"];
            str += hdi["Caption"];
            if (cdr != null && cdr["Name"] != null)
            {
                str += cdr["Name"];
            }
            return Util.GetMD5(str);
        }

        public static string GetLocalIPAddress()
        {
            string ret = "";
            ManagementObject mo = GetNetCardMO();
            if (mo != null)
            {
                string[] mIPAddress = mo["IPAddress"] as string[];
                ret = mIPAddress[0];
                mo.Dispose();
            }
            return ret;
        }

        public static string GetLocalMacAddress()
        {
            string ret = "";
            ManagementObject mo = GetNetCardMO();
            if (mo != null)
            {
                ret = mo["MACAddress"] as string;
                mo.Dispose();
            }
            return ret;
        }

        private static ManagementObject GetNetCardMO()
        {
            ManagementObject ret = null;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption,ServiceName,MACAddress,IPAddress FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=TRUE");
            ManagementObjectCollection moc_nac = searcher.Get();
            foreach (ManagementObject mo in moc_nac)
            {
                string s = (mo["ServiceName"] as string).ToLower();
                //string mCaption = mo["Caption"] as string;
                //string mMACAddress = mo["MACAddress"] as string;
                string[] mIPAddress = mo["IPAddress"] as string[];
                //过滤非真实的网卡
                if (s.Contains("vmnet") || s.Contains("ppoe") || s.Contains("bthpan")
                    || s.Contains("vpn") || s.Contains("ndis") || s.Contains("vnic")
                    || Array.IndexOf(mIPAddress, "0.0.0.0") >= 0)
                {
                    continue;
                }
                ret = mo;
                break;
            }
            return ret;
        }

        public static ManagementObject GetFirstMO(string sql)
        {
            ManagementObject ret = null;
            foreach (ManagementObject mo in GetMO(sql))
            {
                ret = mo;
                break;
            }
            return ret;
        }

        public static ManagementObjectCollection GetMO(string sql)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(sql);
            return searcher.Get();
        }

        /// <summary>
        /// 获取字符串中汉字的个数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetStringLen(string str)
        {

            //获取字符长度，汉字算2个长度，全角字符算2个长度

            int count = 0;

            for (int i = 0; i < str.Length; i++)
            {
                if (IsChina(str[i]))

                    count += 1;
            }

            return count;

        }

        //验证字符是否为汉字

        static public bool IsChina(char chr)
        {

            if (Convert.ToInt32(chr) < Convert.ToInt32(Convert.ToChar(128)))
            {

                return false;

            }

            else
            {

                return true;

            }

        }


        /// <summary>
        /// 截取指定字节长度
        /// </summary>
        /// <param name="pstr"></param>
        /// <param name="Num"></param>
        /// <returns></returns>
        public static string CutByteString(string pstr, int num)
        {

            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(pstr);
            int n = 0;
            int i = 0;
            for (; i < bytes.GetLength(0) && n < num; i++)
            {
                if (i % 2 == 0)
                    n++;
                else
                {
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }
            }
            if (i % 2 == 1)
            {
                if (bytes[i] > 0)
                    i = i - 1;
                else
                    i = i + 1;
            }
            return System.Text.Encoding.Unicode.GetString(bytes, 0, i);
        }


        /// <summary>
        /// 验证是否为数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg
                = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
            return reg.IsMatch(str);
        }
        ///<summary>
        ///验证输入的数据是不是正整数
        ///</summary>
        ///<param name="str">传入字符串</param>
        ///<returns>返回true或者false</returns>
        public static bool IsNumericInteger(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 正数(包括小数)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsPositive(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9].*$");
            bool bl = reg1.IsMatch(str);
            if (bl)
            {
                if (Convert.ToDecimal(str) <= 0)
                {
                    bl = false;
                }
            }
            return bl;
        }


        public static void GetBirth(string identityCard, out DateTime birthday, out string sex)
        {
            birthday = Convert.ToDateTime("1900-1-1 00:00:00");
            sex = string.Empty;
            if (identityCard.Length == 18)//处理18位的身份证号码从号码中得到生日和性别代码
            {
                birthday = Convert.ToDateTime(identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2));
                sex = identityCard.Substring(14, 3);
            }
            if (identityCard.Length == 15)
            {
                birthday = Convert.ToDateTime("19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2));
                sex = identityCard.Substring(12, 3);
            }
            if (sex != "")
            {
                if (int.Parse(sex) % 2 == 0)//性别代码为偶数是女性奇数为男性
                {
                    sex = "F";
                }
                else
                {
                    sex = "M";
                }
            }

        }

        public static bool IsIdCard(string idStr)
        {
            string date = "", Ai = "";
            string verify = "10x98765432";
            int[] Wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            string[] area = { "", "", "", "", "", "", "", "", "", "", "", "北京", "天津", "河北", "山西", "内蒙古", "", "", "", "", "", "辽宁", "吉林", "黑龙江", "", "", "", "", "", "", "", "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", "", "", "", "河南", "湖北", "湖南", "广东", "广西", "海南", "", "", "", "重庆", "四川", "贵州", "云南", "西藏", "", "", "", "", "", "", "陕西", "甘肃", "青海", "宁夏", "新疆", "", "", "", "", "", "台湾", "", "", "", "", "", "", "", "", "", "香港", "澳门", "", "", "", "", "", "", "", "", "国外" };
            string[] re = Regex.Split(idStr, @"^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$", RegexOptions.IgnoreCase);
            if (re.Length != 9) return false;
            int ProvId = int.Parse(re[1]);
            if (ProvId >= area.Length || area[ProvId] == "") return false;
            if (re[2].Length == 12)
            {
                Ai = idStr.Substring(0, 17);
                date = re[4] + "-" + re[5] + "-" + re[6];
            }
            else
            {
                Ai = idStr.Substring(0, 6) + "19" + idStr.Substring(6);
                date = "19" + re[4] + "-" + re[5] + "-" + re[6];
            }
            try
            {
                DateTime.Parse(date);
            }
            catch
            {
                return false;
            }
            int sum = 0;
            for (int i = 0; i <= 16; i++)
            {
                sum += int.Parse(Ai.Substring(i, 1)) * Wi[i];
            }
            Ai += verify.Substring(sum % 11, 1);
            return (idStr.Length == 15 || idStr.Length == 18 && idStr.ToLower() == Ai);
        }

        /// <summary>
        /// 剪切图片
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="width">剪切图片后的宽度</param>
        /// <param name="height">剪切图片后的高度</param>
        /// <param name="mode">剪切方式</param>    
        //public static Image MakeThumbPhoto(string originalImagePath, int width, int height, string mode)
        //{
        //    System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        //    int towidth = width;
        //    int toheight = height;

        //    int x = 0;
        //    int y = 0;
        //    int ow = originalImage.Width;
        //    int oh = originalImage.Height;

        //    switch (mode)
        //    {
        //        case "HW"://指定高宽缩放（可能变形）                
        //            break;
        //        case "W"://指定宽，高按比例                    
        //            toheight = originalImage.Height * width / originalImage.Width;
        //            break;
        //        case "H"://指定高，宽按比例
        //            towidth = originalImage.Width * height / originalImage.Height;
        //            break;
        //        case "Cut"://指定高宽裁减（不变形）                
        //            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
        //            {
        //                oh = originalImage.Height;
        //                ow = originalImage.Height * towidth / toheight;
        //                y = 0;
        //                x = (originalImage.Width - ow) / 2;
        //            }
        //            else
        //            {
        //                ow = originalImage.Width;
        //                oh = originalImage.Width * height / towidth;
        //                x = 0;
        //                y = (originalImage.Height - oh) / 2;
        //            }
        //            break;
        //        default:
        //            break;
        //    }

        //    //新建一个bmp图片
        //    System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //    //新建一个画板
        //    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //    //设置高质量插值法
        //    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //    //设置高质量,低速度呈现平滑程度
        //    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //    //清空画布并以透明背景色填充
        //    g.Clear(System.Drawing.Color.Transparent);

        //    //在指定位置并且按指定大小绘制原图片的指定部分
        //    g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
        //        new System.Drawing.Rectangle(x, y, ow, oh),
        //        System.Drawing.GraphicsUnit.Pixel);

        //    originalImage.Dispose();
        //    //bitmap.Dispose();
        //    g.Dispose();



        //    return bitmap;
        //}


        #region 全角半角转换
        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>全角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToSBC(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }


        /// <summary> 转半角的函数(DBC case) </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>半角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }
        #endregion

        public static List<string> GetFiles(string path, string[] ext)
        {
            List<string> imageFiles = new List<string>();
            string[] files = Directory.GetFiles(path);
            foreach (string file in files)
            {
                string fext = Path.GetExtension(file).ToLower();
                if (Array.IndexOf(ext, fext) >= 0)
                {
                    imageFiles.Add(file);
                }
            }
            return imageFiles;
        }

        //public static void MoveRowUp(GridView view)
        //{
        //    if (!view.IsFirstRow)
        //    {
        //        int pos = view.FocusedRowHandle;
        //        int sort = Convert.ToInt32(view.GetDataRow(pos)["Sort"].ToString());
        //        int presort = Convert.ToInt32(view.GetDataRow(pos - 1)["Sort"]);
        //        view.SetRowCellValue(pos, "Sort", presort);
        //        view.SetRowCellValue(pos - 1, "Sort", sort);
        //        view.FocusedRowHandle = pos - 1;
        //    }
        //}

        //public static void MoveRowDown(GridView view)
        //{
        //    if (!view.IsLastRow)
        //    {
        //        int pos = view.FocusedRowHandle;
        //        int sort = Convert.ToInt32(view.GetFocusedDataRow()["Sort"].ToString());
        //        int aftersort = Convert.ToInt32(view.GetDataRow(pos + 1)["Sort"]);
        //        view.SetRowCellValue(pos, "Sort", aftersort);
        //        view.SetRowCellValue(pos + 1, "Sort", sort);
        //        view.FocusedRowHandle = pos + 1;
        //    }
        //}
        /// <summary>
        /// 将字符串转换为UTF8格式
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToUTF8(string s)
        {
            byte[] buffer = Encoding.GetEncoding("utf-8").GetBytes(s);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in buffer)
            {//换行特殊处理
                if (b == '\n')
                    sb.Append("\n");
                else
                    sb.AppendFormat("%{0:X}", b);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 从Excel文件读取数据到dataset
        /// </summary>
        /// <param name="strExcelFileName">Excel文件路径</param>
        /// <param name="strSheetName">要读取的表名，如果为空则是所有的sheet</param>
        /// <returns></returns>
        public static DataSet ExcelToDataSet(string strExcelFileName, string strSheetName)
        {
            //源的定义
            string strConn = "Provider=Microsoft.Jet.OLEDb.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";


            //定义存放的数据表
            DataSet ds = new DataSet();
            //连接数据源
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            if (string.IsNullOrEmpty(strSheetName))//读取所有的 sheet
            {

                //获取Sheet的名字。   
                DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
                //schemaTable.Rows.Count值为Sheet的总数   

                List<string> tableNames = new List<string>();

                //注意schemaTable是从0开始，即第0个是第1个Sheet。第2列是Sheet名。   
                for (int i = 0; i < schemaTable.Rows.Count; i++)
                {
                    string s = schemaTable.Rows[i][2].ToString().Trim();
                    tableNames.Add(s);

                }
                conn.Close();
                foreach (string tableName in tableNames)
                {
                    string query = string.Format("SELECT   *   FROM  [{0}]", tableName);

                    OleDbCommand oleCommand = new OleDbCommand(query, conn);
                    OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);

                    //   将   Excel   的[Sheet1]表内容填充到   DataSet   对象    
                    oleAdapter.Fill(ds, tableName);
                }
            }
            else
            {
                //Sql语句
                string strExcel = string.Format("select * from [{0}$]", strSheetName);
                //string strExcel = "select * from   [sheet1$]";
                OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
                adapter.Fill(ds, strSheetName);
                //适配到数据源 
            }
            conn.Close();
            return ds;
        }
        /// <summary>
        /// 从Excel文件读取数据到dataset
        /// </summary>
        /// <param name="strExcelFileName">Excel文件路径</param>
        /// <param name="strSheetName">要读取的表名，如果为空则是所有的sheet</param>
        /// <returns></returns>
        public static DataTable ExcelToDataTableFirstSheet(string strExcelFileName)
        {
            //源的定义
            string strConn = "Provider=Microsoft.Jet.OLEDb.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";


            //定义存放的数据表
            DataSet ds = new DataSet();
            //连接数据源
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
            if (schemaTable == null || schemaTable.Rows.Count < 1 || schemaTable.Rows[0][2] == DBNull.Value)
                return null;
            string strSheetName = schemaTable.Rows[0][2].ToString().Trim();
            //Sql语句
            string strExcel = string.Format("select * from [{0}]", strSheetName);
            //string strExcel = "select * from   [sheet1$]";
            OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
            adapter.Fill(ds, strSheetName);
            //适配到数据源  
            conn.Close();
            if (ds == null || ds.Tables.Count < 1)
                return null;
            return ds.Tables[0];
        }
        #region 读取Csv文件返回DataSet
        /// <summary>   
        /// 读取Csv文件返回DataSet   
        /// </summary>   
        /// <param name="sql">查询语句 </param>   
        /// <param name="FilePath">文件路径 </param>   
        /// <returns>Csv内容</returns>          
        public static DataTable CsvReader(string FilePath)
        {
            DataSet CsvData = new DataSet();
            OleDbConnection OleCon = new OleDbConnection();
            OleCon.ConnectionString = @"Provider=Microsoft.Jet.OLEDb.4.0;Data Source=" + FilePath.Substring(0, FilePath.LastIndexOf('\\')) + ";Extended Properties='text;HDR=YES;FMT=Delimited'";

            OleCon.Open();
            OleDbCommand OleCmd = new OleDbCommand("select * from [" + FilePath.Substring(FilePath.LastIndexOf('\\') + 1) + "]", OleCon);
            OleDbDataAdapter OleDa = new OleDbDataAdapter(OleCmd);
            try
            {
                OleDa.Fill(CsvData, "Csv");
                return CsvData.Tables[0];
            }
            catch
            {
                return null;
            }
            finally
            {
                OleCon.Close();
                OleCmd.Dispose();
                OleDa.Dispose();
                OleCon.Dispose();
            }
        }
        #endregion
        public static bool isMobileNo(string mobileNoString)
        {
            string regexFormat = "^[1][0-9]{10}$";
            if (Regex.IsMatch(mobileNoString, regexFormat))
                return true;
            else
                return false;
        }

        #region 获取网络url访问后的结果
        public static string GetUrlRespons(string url)
        {
            //http请求到返回结果
            try
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                Stream sIn = httpResponse.GetResponseStream();
                StreamReader sRead = new StreamReader(sIn);
                string result = sRead.ReadToEnd();
                sRead.Close();
                sRead.Close();
                sIn.Close();
                httpResponse.Close();
                httpRequest = null;
                return result;
            }
            catch { return ""; }
            //return new StreamReader(HttpWebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd();
        }
        #endregion

        /// <summary>      
        /// dataTable转换成Json格式      
        /// </summary>      
        /// <param name="dt"></param>      
        /// <returns></returns>      
        public static string ToJson(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"");
            sb.Append(dt.TableName.ToString());
            sb.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    sb.Append("\"");
                    sb.Append(dt.Columns[j].ColumnName);
                    sb.Append("\":\"");
                    sb.Append(dt.Rows[i][j].ToString());
                    sb.Append("\",");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("]");
            sb.Append("}");
            return sb.ToString();
        }

        /// <summary>      
        /// dataRow转换成Json格式      
        /// </summary>      
        /// <param name="dt"></param>      
        /// <returns></returns>      
        public static string ToJson(DataRow dr)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            for (int j = 0; j < dr.Table.Columns.Count; j++)
            {
                sb.Append("\"");
                sb.Append(dr.Table.Columns[j].ColumnName);
                sb.Append("\":\"");
                sb.Append(dr[j].ToString());
                sb.Append("\",");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("}");
            return sb.ToString();
        }


        public static String GetEnumDesc(Enum e)
        {
            FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
            DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.
                GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (EnumAttributes.Length > 0)
            {
                return EnumAttributes[0].Description;
            }
            return e.ToString();
        }
        ///// <summary>
        ///// 十六进制颜色值转为Color对象 小米
        ///// </summary>
        ///// <param name="colorName">十六进制颜色值</param>
        ///// <returns>Color对象</returns>
        //public static Color ConvertToColor(string colorName)
        //{

        //    if (!colorName.StartsWith("#"))
        //        return Colors.Black;
        //    else
        //        colorName = colorName.Replace("#", string.Empty);

        //    int v = int.Parse(colorName, System.Globalization.NumberStyles.HexNumber);
        //    return new Color()
        //    {
        //        A = Convert.ToByte((v >> 24) & 255),
        //        R = Convert.ToByte((v >> 16) & 255),
        //        G = Convert.ToByte((v >> 8) & 255),
        //        B = Convert.ToByte((v >> 0) & 255)
        //    };
        //}


        /// <summary>
        /// 数值小于0时返回0
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        public static decimal ReturnZero(decimal dc)
        {
            if (dc < 0)
            {
                return 0.00M;
            }
            return dc;
        }

        /// <summary>
        /// 根据枚举获取列表
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static Dictionary<string, int> GetEnumToList(Type enumType)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();
            foreach (int i in Enum.GetValues(enumType))
            {
                string name = string.Empty;
                DescriptionAttribute dna = null;
                FieldInfo fi = enumType.GetField(Enum.GetName(enumType, i));
                dna = (DescriptionAttribute)Attribute.GetCustomAttribute(
                   fi, typeof(DescriptionAttribute));

                if (dna != null && string.IsNullOrEmpty(dna.Description) == false)
                {
                    name = dna.Description;
                }

                //取显示名称
                result.Add(name, i);

            }
            return result;
        }

        /// <summary>
        /// 根据枚举值获取此值对应的Description的值
        /// </summary>
        ///<param name="enumValue">枚举的值</param>
        /// <returns></returns>
        public static string GetEnumDescription<T>(int enumValue)
        {

            var enumType = typeof(T);
            var vs = Enum.GetValues(enumType);
            foreach (int i in vs)
            {
                if (Convert.ToInt32(vs.GetValue(i)) == enumValue)
                {
                    string name = string.Empty;
                    DescriptionAttribute dna = null;
                    FieldInfo fi = enumType.GetField(Enum.GetName(enumType, i));

                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(
                       fi, typeof(DescriptionAttribute));

                    if (dna != null && string.IsNullOrEmpty(dna.Description) == false)
                    {
                        name = dna.Description;
                    }
                    return name;
                }

            }
            return "";
        }

        #region 二维码
        [DllImport("QRDll.dll")]
        public static extern ulong GenerateQRFile(int nLevel, int nMode, int nVersion, string szData, string FileName);  //生成二维码图片
        static object obj = new Object();
        public static ulong CreateTwoCodeFile(int nLevel, int nMode, int nVersion, string szData, string FileName)
        {
            lock (obj)
            {
                return GenerateQRFile(nLevel, nMode, nVersion, szData, FileName);
            }
        }
        #endregion

        public static UInt32 IP2Int(string ipStr)
        {
            string[] ip = ipStr.Split('.');
            uint ipCode = 0xFFFFFF00 | byte.Parse(ip[3]);
            ipCode = ipCode & 0xFFFF00FF | (uint.Parse(ip[2]) << 8);
            ipCode = ipCode & 0xFF00FFFF | (uint.Parse(ip[1]) << 16);
            ipCode = ipCode & 0x00FFFFFF | (uint.Parse(ip[0]) << 24);
            return ipCode;
        }
        public static UInt32 GetCardNoByWigan(UInt32 intSource)
        {
            //如果是韦根34
            if (Session.IsCardUse34)
                return intSource;
            else//是韦根26
            {
                //var s = string.Format("{0}&0x00FFFFFF", intSource);
                return intSource & 0x00FFFFFF;
                //return UInt32.Parse(s);
            }
        }
    }
}
